<template>
  <div>
    <el-dialog title="缺陷" :visible.sync="dialogVisible" width="45%">
      <div>
        <!-- <div>
          <el-steps :active="active">
            <el-step title="待提交"></el-step>
            <el-step title="待消缺"></el-step>
            <el-step title="待验收"></el-step>
            <el-step title="驳回"></el-step>
            <el-step title="完成"></el-step>
          </el-steps>
        </div>
        <el-divider></el-divider> -->
        <div class="title">
          <div class="twohig">登记情况</div>
          <div class="twohigno"></div>
        </div>
        <el-form ref="form" :model="formdata" :rules="rules" label-width="100px" :disabled="flag">
          <el-row>
            <el-col :span="12">
              <el-form-item label="用电企业" prop="orgName">
                <el-select v-model="formdata.orgName" size="small" filterable style="width: 100%;" >
                  <el-option label="bizOrgName" value="bizOrgNo" class="option">
                    <el-tree :data="data" :props="propss" @node-click="handleNodeClick"></el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备" prop="equipName">
                <el-select v-model="formdata.equipName"  size="small" style="width: 100%;" ref="renyuan">
                  <el-option class="option" :label="formdata.equipName" :value="formdata.id" >
                        <el-tree
                        :props="propss"
                        :load="loadNodess"
                        lazy
                        @node-click="handleNode"
                        ref="tree">
                        </el-tree>
                      </el-option>
                  </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row >
            <el-col :span="12">
              <el-form-item label="缺陷等级" prop="level">
                <el-select v-model="formdata.level" size="small" filterable style="width: 100%;" @change="handleSelectChange">
                  <el-option label="一般" value="0" />
                  <el-option label="重要" value="1" />
                  <el-option label="紧急" value="2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row >
            <el-col :span="24">
              <el-form-item label="缺陷现象" prop="defectDescription">
                <el-input v-model="formdata.defectDescription" type="textarea" placeholder="请输入问题描述" ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row >
              <el-col :span="12">
                <el-form-item label="发现人" prop="discovererName">
                  <el-input v-model="formdata.discovererName" placeholder="请输入发现人" size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发现时间" prop="findDate">
                  <el-input v-model="formdata.findDate" placeholder="请选择发现时间" suffix-icon="el-icon-date" :disabled="true" size="small"></el-input>
                </el-form-item>
              </el-col>
          </el-row>
          <el-row >
              <el-col :span="12">
                <el-form-item label="处理期限" prop="processDeadlineDate">
                  <el-date-picker
                    v-model="formdata.processDeadlineDate"
                    size="small"
                    type="datetime"
                    style="width: 100%;"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="选择日期时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="安排消缺人" prop="solveUserCode">
                  <el-select v-model="formdata.solveUserCode" size="small" filterable style="width: 100%;" >
                    <el-option v-for="(item, index) in xiaoandyanlist" :key="index" :label="item.userName" :value="item.userNO" ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
          </el-row>
          <div class="fujian">附件</div>
          <div class="uplod">
                <ElUplod @getuplodimg="getuplodimg" :fileList="fileList"></ElUplod>
          </div>
          <el-row >
              <el-col :span="12">
                <el-form-item label="缺陷编号" prop="code">
                 <el-input v-model="formdata.code" size="small" placeholder="" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="填报部门" prop="createDepartmentname">
                 <el-input v-model="createDepartmentname" size="small" placeholder="" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
          </el-row>
          <el-row >
              <el-col :span="12">
                <el-form-item label="填报人" prop="createUsername">
                 <el-input v-model="createUsername" size="small" placeholder="" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="填报时间" prop="createDate">
                 <el-input v-model="formdata.createDate" size="small" placeholder="" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
          </el-row>
        </el-form>
        <div v-if="active>2">
          <ChuLi @toquxiao="dialogVisible = false" ref="ChuLirefs" :active="active"
          :xiaoandyanlist="xiaoandyanlist" :formdata="formdata" @tosuccess="tosuccess"></ChuLi>
        </div>
        <div v-if="active>4">
          <YanShou @toquxiao="dialogVisible = false" ref="YanShourefs" :active="active"
          :xiaoandyanlist="xiaoandyanlist" :formdata="formdata" @tosuccess="tosuccess"></YanShou>
        </div>
        <div class="dialog-footer" v-show="active==1&&!flag">
          <span>
            <el-button size="small" type="primary" v-show="!flag&&isupdate&&!issubmit" @click="sureupdate">确 定</el-button>
            <el-button size="small" type="primary" v-show="!flag&&issubmit&&isupdate" @click="totijiao">提 交</el-button>
            <el-button size="small" type="primary" v-show="!flag&&!isupdate" @click="tosubmit(0)">保 存</el-button>
            <el-button size="small" type="primary" v-show="!flag&&!isupdate" @click="tosubmit(1)">保存并提交</el-button>
            <el-button size="small" @click="dialogVisible = false">取 消</el-button>
          </span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import ElUplod from './elupload'
import { getloginuserapi } from '@/api/cycle'
import dayjs from 'dayjs'
import {base64ToFile,base64ToBlob} from '@/utils/tofile'
import {getxiaoquelistapi,getcodeapi,postadddefectapi,postimguplodapi,getarrdefectimgapi,postupdatelistapi,posttijiaolistapi} from '@/api/system/defectManage'
import {getCompanyInfo} from '@/api/layout'
import YanShou from './yanshou.vue'
import ChuLi from './chuli.vue'
import { getgenjiedianapi, getzijidianapi } from '@/api/monitor'
export default {
  name: 'CallPoliceIndexto',
  components: {
    ChuLi,
    ElUplod,
    YanShou
  },
  data() {
    return {
      data:{},
      propss: {
        label: 'name',
        disabled:'disabled'
      },
      flag: false,
      issubmit:false,
      isupdate:false,
      userinfo:{},
      formdata: {},
      active: 1,
      xiaoandyanlist:[],
      fileList:[],
      dialogVisible: false,
      createUsername:'',
      createDepartmentname: '',
      rules: {
        orgName: [{ required: true, message: '请选择用电企业', trigger: 'change' }],
        equipName: [{ required: true, message: '请选择设备', trigger: 'change' }],
        level: [{ required: true, message: '请选择缺陷等级', trigger: 'change' }],
        defectDescription: [{ required: true, message: '请输入缺陷现象', trigger: 'blur' }],
        discovererName: [{ required: true, message: '请输入发现人', trigger: 'blur' }],
        findDate: [{ required: true, message: '请选择发现时间', trigger: 'change' }],
        processDeadlineDate: [{ required: true, message: '请选择处理期限', trigger: 'change' }],
        solveUserCode: [{ required: true, message: '请选择消缺人', trigger: 'change' }],
      }
    }
  },

  async mounted() {
    const { data: { list } } = await getCompanyInfo()
    this.data=list
    
  },

  methods: {
    // 保存/保存并提交
    async tosubmit(val) {
      await this.$refs.form.validate()
      const createPictureIds=await this.getcreatedids()
      await postadddefectapi({
        ...this.formdata,createUserCode: this.userinfo.userNo, state: val, createPictureIds
      }).then(res => {
        this.setmessage(res,`${val==1?'新增并提交成功':'新增成功'}`)
      })
    },
    // 确认修改
    async sureupdate() {
      const {createDate,defectDescription,discovererName,equipId,equipName,findDate,id,level,orgNo,processDeadlineDate,solveUserCode}=this.formdata
      const createPictureIds=await this.getcreatedids()
      await postupdatelistapi({
        createDate, defectDescription, discovererName, equipId, equipName, findDate, id, level,
        orgNo, processDeadlineDate, solveUserCode, createPictureIds
      }).then(res => {
        this.setmessage(res,`修改成功`)
      })
    },
    // 批量上传图片获取id
    async getcreatedids() {
      let formData = new FormData();  
      this.fileList.forEach(ele => {
        formData.append('uploadFile', ele.raw)
      })
      const { data: { entity: createPictureIds } } = await postimguplodapi(formData)
      return createPictureIds
    },
    // 提交
    async totijiao() {
      const { data: { entity: userinfo } } = await getloginuserapi()
      await posttijiaolistapi({
        createUserCode: userinfo.userNo,id:this.formdata.id,submitDate:this.gettime()
      }).then(res => {
        this.setmessage(res,`提交成功`)
      })
    },
    // 新增
    async adddefect() {
      this.active=1
      this.dialogVisible = true
      const { data: { entity } } = await getcodeapi()
      this.$set(this.formdata,'code',entity)
      this.$set(this.formdata, 'findDate', this.gettime())
      this.$set(this.formdata, 'createDate', this.gettime())
      const { data: { entity: userinfo } } = await getloginuserapi()
      this.$set(this, 'createUsername', userinfo.userName)
      this.$set(this, 'createDepartmentname', userinfo.deptName)
      this.$set(this.formdata, 'createDepartmentCode', userinfo.deptNo)
      this.userinfo=userinfo
    },
    // 提交/浏览
    async tolooks(val, row, flag) {
      this.active=val
      this.flag = flag
      this.$set(this, 'createUsername', row.createUserName)
      this.$set(this, 'createDepartmentname', row.createDepartmentName)
      await this.getxiaoquelist(row.orgNo)
      this.formdata = { ...row }
      this.dialogVisible = true
      const { data: { list } } = await getarrdefectimgapi({ id: row.id, type: 0 })
      list.forEach(ele => {
        this.fileList.push({
          raw: new File([base64ToBlob('data:image/jpeg;base64,' + ele.fileData)], ele.fileName),
          url:'data:image/jpeg;base64,'+ele.fileData,
          name:ele.fileName
        })
      })
      if (val < 2) return ''
      if(val==4) return this.$refs.ChuLirefs?.tolook(row, true)
      if (flag||val==5) {
        this.$refs.ChuLirefs?.tolook(row, flag)
      } else {
        this.$refs.ChuLirefs?.xiaoque(row,flag)
        this.$refs.ChuLirefs.isshow=true
      }
      if (val < 4) return ''
      if (flag) {
        this.$refs.YanShourefs?.tolook(row,flag)
      } else {
        this.$refs.YanShourefs?.look(row, flag)
        this.$refs.YanShourefs.isshow=true
      }
    },
    // 图片上传
    getuplodimg(fileList) {
      this.fileList=fileList
    },
    // 修改
    toupdate(val, row, flag) {
      this.issubmit=flag
      this.isupdate=true
      this.tolooks(val, row)
    },
    // 设备树选择
    handleNode(val) {
      this.$set(this.formdata, 'equipName', val.name)
      this.$set(this.formdata, 'equipId', val.id)
    },
    // 人员树选择
    handleNodeClick(val) {
      this.$set(this.formdata,'orgName', val.name)
      this.$set(this.formdata, 'orgNo', val.id)
      this.$set(this.formdata, 'solveUserCode', ' ')
      this.getxiaoquelist(val.id)
    },
    // 获取消缺人
    async getxiaoquelist(id) {
      const { data: { list: array } } = await getxiaoquelistapi({orgNo:id})
      this.xiaoandyanlist = array
    },
    // 树组件懒加载
    async loadNodess(node, resolve) {
      const res = await getgenjiedianapi({ treeModel: 'DeviceManageTree' })
      if (node.level === 0) {
        const ress = await getzijidianapi(res.data.list[0])
        return resolve(ress.data.list)
      }
      if (node.level > 0) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      }
    },
    // 弹窗取消
    quxiao() {
      this.flag = false
      this.issubmit=false
      this.isupdate=false
      this.fileList=[]
      this.createUsername='',
      this.createDepartmentname = ''
      this.$refs.form.resetFields()
      this.formdata = this.$options.data().formdata
      this.$refs.ChuLirefs?.quxiao()
      this.$refs.YanShourefs?.quxiao()
    },
    // 获取当前时间
    gettime() {
      return dayjs().format('YYYY-MM-DD HH:mm:ss')
    },
    // 根据消缺等级获取处理期限时间
    handleSelectChange() {
      const today = dayjs();
      let newDate;
      switch (this.formdata.level) {
        case '0': // 一般
          newDate = today.add(180, 'day');
          break;
        case '1': // 重要
          newDate = today.add(30, 'day');
          break;
        case '2': // 紧急
          newDate = today.add(1, 'day');
          break;
        default:
          newDate = today;
          break;
      }
      this.$set(this.formdata,'processDeadlineDate',newDate.format('YYYY-MM-DD HH:mm:ss'))
    },
    setmessage(res,name) {
      if (res.code == '200') {
          this.quxiao()
          this.dialogVisible = false 
          this.$emit('getlist')
        }
        this.$message({
          type: res.code == '200' ? 'success' : 'warning',
          message: res.code == '200' ? name:res.message
        })
    },
    tosuccess(res, name) {
      this.setmessage(res, name)
    }
  },
  watch: {
    dialogVisible(val) {
      if(!val) this.quxiao()
    }
  }
}
</script>
<style lang="scss" scoped>
.title {
  color: #1890ff;
  height: 32px;
  display: flex;
  margin-bottom: 15px;
  .twohig {
    width: 80px;
    line-height: 32px;
    text-align: center;
    border: 1px solid #ccc;
    border-bottom: none;
    border-radius: 3px 3px 0 0;
  }
  .twohigno {
    flex: 1;
    height: 32px;
    border-bottom: 1px solid #ccc;
  }
}
.fujian{
  height: 40px;
  line-height: 40px;
  padding-left: 20px;
  border: 1px solid #ccc;
}
.uplod{
  border: 1px solid #ccc;
  padding: 30px;
  border-top: none;
  margin-bottom: 15px;
}
.dialog-footer {
  text-align: center;
}
.option{
  height: auto;
}
</style>
